package entity

import (
	"time"

	"github.com/bytedance/sonic"
)

const (
	// WorkflowUnderReviewStatus 审批中
	WorkflowUnderReviewStatus = 1
	// WorkflowPassedReviewStatus 审批通过
	WorkflowPassedReviewStatus = 2
	// WorkflowTempRejectedStatus 临时驳回
	WorkflowTempRejectedStatus = -3
	// WorkflowArchiveStatus 归档
	WorkflowArchiveStatus = -10
	// WorkflowCanceledStatus 已撤销
	WorkflowCanceledStatus = -5
	// WorkflowDraftStatus 草稿
	WorkflowDraftStatus = -2
)

// Workflow 审批流模板启动后成为workflow
type Workflow struct {
	ID string `json:"id"`

	// Status 审批流状态，1:审批中, 2:审批通过, -1:审批拒绝
	Status int `json:"status"`

	// WorkflowTemplateID 审批流模板ID
	WorkflowTemplateID string `json:"workflowTemplateId"`

	// SponsorID 发起用户ID
	SponsorID string `json:"sponsorId"`

	// FormContent 审批启动时提交的表单内容
	FormContent string `json:"formContent"`

	// BusinessID 对外关联的业务ID
	BusinessID string `json:"businessId"`

	// BusinessCode 对外关联的业务编码
	BusinessCode string `json:"businessCode"`

	// CurrentNodeID 当前审批所处的节点
	CurrentNodeID string `json:"currentNodeId"`

	// BusinessParams 业务数据
	BusinessParams string `json:"businessParams"`

	// Conclusion 工作流最后结论（当前为最后一个审批任务的评论）
	Conclusion string `json:"conclusion"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

func (w *Workflow) IsValidToReview(nodeID string) bool {
	if w.Status != WorkflowUnderReviewStatus {
		return false
	}

	if w.CurrentNodeID != nodeID {
		return false
	}

	return true
}

func (w *Workflow) Pass(conclusion string) {
	w.Status = WorkflowPassedReviewStatus
	w.Conclusion = conclusion
	w.CurrentNodeID = "PASSED"
}

func (w *Workflow) TempReject(conclusion string) {
	w.Status = WorkflowTempRejectedStatus
	w.Conclusion = conclusion
}

func (w *Workflow) Archive() {
	w.Status = WorkflowArchiveStatus
}

func (w *Workflow) IsValidToUpdateContent() bool {
	return w.Status == WorkflowUnderReviewStatus
}

func (w *Workflow) SetFormContent(formContent string) {
	w.FormContent = formContent
}

func (w *Workflow) SetBusinessParams(params string) {
	w.BusinessParams = params
}

func (w *Workflow) Cancel() {
	w.Status = WorkflowCanceledStatus
}

// SetDraft 设置工作流为草稿状态
func (w *Workflow) SetDraft() {
	w.Status = WorkflowDraftStatus
}

// GetConditionParams 从FormContent中提取条件参数
// FormContent应该是一个JSON字符串，该方法将其解析为map[string]any用于条件判断
// 返回值：
//   - conditionParams: 条件参数映射表，用于条件节点的判断逻辑
//   - error: 解析错误
func (w *Workflow) GetConditionParams() (ConditionParams, error) {
	// 步骤1：检查FormContent是否为空
	if w.FormContent == "" {
		return make(ConditionParams), nil
	}

	// 步骤2：将FormContent解析为map[string]any
	var formData map[string]any
	if err := sonic.UnmarshalString(w.FormContent, &formData); err != nil {
		return nil, err
	}

	// 步骤3：将解析结果转换为ConditionParams类型
	conditionParams := make(ConditionParams)
	for key, value := range formData {
		conditionParams[key] = value
	}

	return conditionParams, nil
}
